<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>个人考试记录 - 智慧教育考试系统</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <!-- 配置Tailwind自定义主题 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#36D399',
            accent: '#FF9F43',
            neutral: '#F8FAFC',
            'neutral-dark': '#334155',
            'status-pending': '#FFB800',
            'status-active': '#36D399',
            'status-expired': '#94A3B8',
            'score-high': '#36D399',
            'score-medium': '#FF9F43',
            'score-low': '#F87171'
          },
          fontFamily: {
            inter: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .card-shadow {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      }
      .nav-hover {
        @apply transition-all duration-300 hover:bg-primary/10 hover:text-primary;
      }
      .btn-primary {
        @apply bg-primary text-white px-4 py-2 rounded-lg transition-all duration-300 hover:bg-primary/90 active:bg-primary/80;
      }
      .btn-secondary {
        @apply bg-white border border-gray-200 text-neutral-dark px-4 py-2 rounded-lg transition-all duration-300 hover:bg-gray-50 active:bg-gray-100;
      }
      .btn-view {
        @apply bg-primary/10 text-primary px-3 py-1.5 rounded-lg transition-all duration-300 hover:bg-primary/20 active:bg-primary/30;
      }
      .progress-bar {
        @apply h-2 rounded-full bg-gray-200 overflow-hidden;
      }
      .progress-value {
        @apply h-full rounded-full transition-all duration-500;
      }
    }
  </style>
</head>
<body class="font-inter bg-gray-50 text-neutral-dark min-h-screen flex flex-col">
  <!-- 顶部导航栏 -->
  <header class="bg-white border-b border-gray-200 sticky top-0 z-30">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
      <div class="flex items-center space-x-2">
        <i class="fa fa-graduation-cap text-primary text-2xl"></i>
        <h1 class="text-xl font-bold text-primary">智慧教育考试系统</h1>
      </div>

      <div class="flex items-center space-x-6">
        <div class="hidden md:flex items-center space-x-4">
          <button class="text-gray-500 hover:text-primary transition-colors relative">
            <i class="fa fa-bell-o"></i>
            <span class="absolute -top-1 -right-1 w-4 h-4 bg-accent text-white text-xs rounded-full flex items-center justify-center">3</span>
          </button>
          <button class="text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-cog"></i>
          </button>
        </div>

        <div class="flex items-center space-x-2">
          <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary">
            <i class="fa fa-user"></i>
          </div>
          <span class="hidden md:inline">李同学</span>
        </div>
      </div>
    </div>
  </header>

  <!-- 主内容区 -->
  <main class="flex-1 flex flex-col md:flex-row">
    <!-- 左侧导航 -->
    <aside class="w-full md:w-64 bg-white border-r border-gray-200 md:h-[calc(100vh-60px)] sticky md:sticky top-[60px] z-20">
      <!-- 角色切换 -->
      <div class="p-4 border-b border-gray-200">
        <h2 class="text-sm font-medium text-gray-500 mb-2">角色切换</h2>
        <div class="flex rounded-lg overflow-hidden border border-gray-200">
          <button id="teacher-tab" class="flex-1 py-2 px-3 bg-white text-gray-600 text-sm font-medium hover:bg-gray-50">
            教师端
          </button>
          <button id="student-tab" class="flex-1 py-2 px-3 bg-primary text-white text-sm font-medium">
            学生端
          </button>
        </div>
      </div>

      <!-- 教师导航菜单 (默认隐藏) -->
      <nav id="teacher-nav" class="p-2 hidden">
        <ul class="space-y-1">
          <li>
            <a href="/home" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-bar-chart w-5 text-center"></i>
              <span>教师控制台</span>
            </a>
          </li>
          <li>
            <a href="/Publish_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-pencil-square-o w-5 text-center"></i>
              <span>发布考试</span>
            </a>
          </li>
          <li>
            <a href="/History_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-history w-5 text-center"></i>
              <span>历史考试</span>
            </a>
          </li>
          <li>
            <a href="/Set_questions" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-magic w-5 text-center"></i>
              <span>一键出题</span>
            </a>
          </li>
          <li>
            <a href="/Question_Bank" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-book w-5 text-center"></i>
              <span>题库管理</span>
            </a>
          </li>
          <li>
            <a href="/stu_management" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-users w-5 text-center"></i>
              <span>学生管理</span>
            </a>
          </li>
          <li>
            <a href="/class_management" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-th-large w-5 text-center"></i>
              <span>班级管理</span>
            </a>
          </li>
        </ul>
      </nav>

      <!-- 学生导航菜单 -->
      <nav id="student-nav" class="p-2">
        <ul class="space-y-1">
          <li>
            <a href="/Exam_record" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover text-primary bg-primary/10">
              <i class="fa fa-file-text-o w-5 text-center"></i>
              <span>个人考试记录</span>
            </a>
          </li>
          <li>
            <a href="/Waiting_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-clock-o w-5 text-center"></i>
              <span>待考试</span>
              <span class="ml-auto bg-accent text-white text-xs px-2 py-0.5 rounded-full">3</span>
            </a>
          </li>
          <li>
            <a href="/Mistake_question" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-exclamation-circle w-5 text-center"></i>
              <span>错题本</span>
            </a>
          </li>
        </ul>
      </nav>
    </aside>

    <!-- 右侧内容区 -->
    <div class="flex-1 p-4 md:p-6 overflow-auto">
      <div class="mb-6">
        <div class="flex items-center">
          <a href="#" class="text-gray-500 hover:text-primary mr-2">
            <i class="fa fa-arrow-left"></i>
          </a>
          <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold">个人考试记录</h2>
        </div>
        <p class="text-gray-500 mt-1">查看所有已参与的考试记录和详细数据</p>
      </div>

      <!-- 学习数据概览 -->
      <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
        <div class="bg-white rounded-xl p-5 card-shadow">
          <div class="flex items-start justify-between">
            <div>
              <p class="text-gray-500 text-sm">总考试次数</p>
              <h3 class="text-2xl font-bold mt-1">24次</h3>
              <p class="text-primary text-sm mt-2 flex items-center">
              </p>
            </div>
            <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
              <i class="fa fa-file-text-o"></i>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-xl p-5 card-shadow">
          <div class="flex items-start justify-between">
            <div>
              <p class="text-gray-500 text-sm">平均得分</p>
              <h3 class="text-2xl font-bold mt-1">82.5分</h3>
              <p class="text-score-high text-sm mt-2 flex items-center">
                <i class="fa fa-arrow-up mr-1"></i> 高于班级平均分4.2分
              </p>
            </div>
            <div class="w-10 h-10 rounded-full bg-score-high/10 flex items-center justify-center text-score-high">
              <i class="fa fa-line-chart"></i>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-xl p-5 card-shadow">
          <div class="flex items-start justify-between">
            <div>
              <p class="text-gray-500 text-sm">优秀率</p>
              <h3 class="text-2xl font-bold mt-1">62.5%</h3>
              <p class="text-primary text-sm mt-2 flex items-center">
                <i class="fa fa-trophy mr-1"></i> 15次考试达到优秀
              </p>
            </div>
            <div class="w-10 h-10 rounded-full bg-accent/10 flex items-center justify-center text-accent">
              <i class="fa fa-star"></i>
            </div>
          </div>
        </div>
      </div>

      <!-- 搜索与筛选区域 -->
      <div class="bg-white rounded-xl p-5 card-shadow mb-6">
        <div class="flex flex-col md:flex-row flex-wrap gap-4">
          <div class="w-full md:w-auto flex items-center gap-3">
            <label class="text-sm font-medium text-gray-700">考试类型：</label>
            <select class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
              <option>全部类型</option>
              <option>每日一测</option>
              <option>周测</option>
              <option>月考</option>
              <option>期中/期末考试</option>
            </select>
          </div>

          <div class="w-full md:w-auto flex items-center gap-3">
            <label class="text-sm font-medium text-gray-700">学科：</label>
            <select class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
              <option>全部学科</option>
              <option>数学</option>
              <option>语文</option>
              <option>英语</option>
              <option>物理</option>
              <option>化学</option>
            </select>
          </div>

          <div class="w-full md:w-auto flex items-center gap-3">
            <label class="text-sm font-medium text-gray-700">考试时间：</label>
            <select class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
              <option>全部时间</option>
              <option>近一周</option>
              <option>近一个月</option>
              <option>近三个月</option>
              <option>近一年</option>
            </select>
          </div>

          <div class="w-full md:flex-1 relative">
            <input type="text" placeholder="搜索考试名称..."
                  class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
            <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
          </div>
        </div>
      </div>

      <!-- 考试记录表格 -->
      <div class="bg-white rounded-xl card-shadow overflow-hidden">
        <div class="overflow-x-auto">
          <table class="w-full min-w-[900px]">
            <thead>
              <tr class="bg-gray-50 text-left">
                <th class="px-6 py-4 text-sm font-medium text-gray-600">序号</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">考试名称</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">考试类型</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">学科</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">考试时间</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">我的得分</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">班级平均分</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">班级排名</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600 text-right">操作</th>
              </tr>
            </thead>
            <tbody class="divide-y divide-gray-100">
              <!-- 考试1 -->
              <tr class="hover:bg-gray-50 transition-colors">
                <td class="px-6 py-4 text-sm text-gray-700">1</td>
                <td class="px-6 py-4 text-sm">
                  <div class="flex items-center">
                    <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary mr-2">
                      <i class="fa fa-file-text-o"></i>
                    </div>
                    <span class="font-medium">试卷名称</span>
                  </div>
                </td>
                <td class="px-6 py-4 text-sm text-gray-700">周测</td>
                <td class="px-6 py-4 text-sm text-gray-700">数学</td>
                <td class="px-6 py-4 text-sm text-gray-700">2025-10-21 14:30-15:30</td>
                <td class="px-6 py-4">
                  <span class="text-score-high font-medium">88分</span>
                </td>
                <td class="px-6 py-4 text-sm text-gray-700">76.5分</td>
                <td class="px-6 py-4 text-sm">
                  <span class="px-2 py-1 bg-primary/10 text-primary text-xs rounded-full">第5名</span>
                </td>
                <td class="px-6 py-4 text-right">
                  <button class="btn-view text-sm flex items-center justify-center" data-exam="高一数学函数章节周测">
                    <i class="fa fa-bar-chart mr-1"></i> 查看试卷
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <!-- 在表格后面添加试卷详情模态框 -->
<!-- 试卷详情模态框 -->
<div id="examDetailModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
  <div class="bg-white rounded-xl w-full max-w-4xl max-h-[90vh] overflow-hidden">
    <!-- 模态框头部 -->
    <div class="bg-primary text-white p-6">
      <div class="flex items-center justify-between">
        <h3 class="text-xl font-bold" id="modalExamTitle">试卷详情</h3>
        <button id="closeModal" class="text-white hover:text-gray-200 text-2xl">
          <i class="fa fa-times"></i>
        </button>
      </div>
      <div class="mt-2 grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
        <div>
          <span class="opacity-80">考试类型：</span>
          <span id="modalExamType"></span>
        </div>
        <div>
          <span class="opacity-80">学科：</span>
          <span id="modalExamSubject"></span>
        </div>
        <div>
          <span class="opacity-80">考试时间：</span>
          <span id="modalExamTime"></span>
        </div>
        <div>
          <span class="opacity-80">得分：</span>
          <span id="modalExamScore" class="font-bold"></span>
        </div>
      </div>
    </div>

    <!-- 模态框内容 -->
    <div class="p-6 overflow-y-auto max-h-[60vh]">
      <div id="questionsContainer" class="space-y-6">
        <!-- 题目会动态加载到这里 -->
      </div>
    </div>

    <!-- 模态框底部 -->
    <div class="border-t border-gray-200 p-4 bg-gray-50">
      <div class="flex justify-end">
        <button id="closeModalBtn" class="btn-secondary">
          关闭
        </button>
      </div>
    </div>
  </div>
</div>
        <!-- 分页 -->
        <div class="px-6 py-4 border-t border-gray-100 flex flex-col sm:flex-row justify-between items-center">
          <p class="text-sm text-gray-500 mb-4 sm:mb-0">显示 1 至 5 条，共 24 条记录</p>
          <div class="flex items-center space-x-1">
            <button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 text-gray-500 hover:border-primary hover:text-primary disabled:opacity-50 disabled:cursor-not-allowed" disabled>
              <i class="fa fa-angle-left"></i>
            </button>
            <button class="w-9 h-9 flex items-center justify-center rounded bg-primary text-white">1</button>
            <button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 hover:border-primary hover:text-primary">2</button>
            <button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 hover:border-primary hover:text-primary">3</button>
            <button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 hover:border-primary hover:text-primary">4</button>
            <button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 hover:border-primary hover:text-primary">5</button>
            <button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 text-gray-700 hover:border-primary hover:text-primary">
              <i class="fa fa-angle-right"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- 学习表现趋势图 -->
      <div class="mt-6 bg-white rounded-xl p-5 card-shadow">
        <div class="flex items-center justify-between mb-6">
          <h3 class="font-bold text-lg">近期考试成绩趋势</h3>

        </div>
        <div class="h-[300px]">
          <canvas id="scoreTrendChart"></canvas>
        </div>
      </div>
    </div>
  </main>

  <!-- 页脚 -->
  <footer class="bg-white border-t border-gray-200 py-4">
    <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
      <p>© 2025 智慧教育考试系统 版权所有</p>
    </div>
  </footer>

  <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
  <script>
    // 全局变量：当前题目ID、学生ID、用户答案、是否已提交
    async function UserIdInfo(){
        try{
            const response = await fetch('/api/current-user');
            const userid = await response.json();
            return userid
        }
        catch (error){
            console.error('加载用户信息失败：',error);
        }
    }
    const STU_ID = UserIdInfo().username; // 实际项目中应从登录态获取
    // 角色切换功能
    const setupRoleSwitch = () => {
      const teacherTab = document.getElementById('teacher-tab');
      const studentTab = document.getElementById('student-tab');
      const teacherNav = document.getElementById('teacher-nav');
      const studentNav = document.getElementById('student-nav');

      studentTab.addEventListener('click', () => {
        // 更新标签样式
        studentTab.classList.add('bg-primary', 'text-white');
        studentTab.classList.remove('bg-white', 'text-gray-600', 'hover:bg-gray-50');
        teacherTab.classList.add('bg-white', 'text-gray-600', 'hover:bg-gray-50');
        teacherTab.classList.remove('bg-primary', 'text-white');

        // 显示学生导航，隐藏教师导航
        studentNav.classList.remove('hidden');
        teacherNav.classList.add('hidden');
      });
    };
// 获取考试记录数据
const fetchExamRecords = async (filters = {}) => {
    try {
        const params = new URLSearchParams();
        if (filters.examType) params.append('exam_type', filters.examType);
        if (filters.subject) params.append('subject', filters.subject);
        if (filters.timeRange) params.append('time_range', filters.timeRange);
        if (filters.search) params.append('search', filters.search);
        if (filters.page) params.append('page', filters.page);
        params.append('page_size', 10);

        const response = await fetch(`/api/exam_records?${params}`);
        const result = await response.json();

        if (result.success) {
            return result.data;
        } else {
            console.error('获取考试记录失败:', result.error);
            return { exams: [], pagination: {}, summary: {} };
        }
    } catch (error) {
        console.error('获取考试记录时出错:', error);
        return { exams: [], pagination: {}, summary: {} };
    }
};

// 获取筛选条件
const fetchFilterOptions = async () => {
    try {
        const response = await fetch('/api/exam_records/filters');
        const result = await response.json();

        if (result.success) {
            return result.data;
        } else {
            console.error('获取筛选条件失败:', result.error);
            return { exam_types: [], subjects: [] };
        }
    } catch (error) {
        console.error('获取筛选条件时出错:', error);
        return { exam_types: [], subjects: [] };
    }
};

// 获取成绩趋势数据
const fetchScoreTrend = async () => {
    try {
        const response = await fetch('/api/exam_records/trend');
        const result = await response.json();

        if (result.success) {
            return result.data;
        } else {
            console.error('获取成绩趋势失败:', result.error);
            return { labels: [], student_scores: [], class_avg_scores: [] };
        }
    } catch (error) {
        console.error('获取成绩趋势时出错:', error);
        return { labels: [], student_scores: [], class_avg_scores: [] };
    }
};

// 渲染考试记录表格
const renderExamTable = (exams) => {
    const tbody = document.querySelector('tbody');
    if (!tbody) return;

    if (exams.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="9" class="px-6 py-8 text-center text-gray-500">
                    <div class="flex flex-col items-center justify-center">
                        <i class="fa fa-file-text-o text-4xl text-gray-300 mb-2"></i>
                        <p>暂无考试记录</p>
                    </div>
                </td>
            </tr>
        `;
        return;
    }

    tbody.innerHTML = exams.map((exam, index) => `
        <tr class="hover:bg-gray-50 transition-colors">
            <td class="px-6 py-4 text-sm text-gray-700">${exam.id}</td>
            <td class="px-6 py-4 text-sm">
                <div class="flex items-center">
                    <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary mr-2">
                        <i class="fa fa-file-text-o"></i>
                    </div>
                    <span class="font-medium">${exam.exam_name}</span>
                </div>
            </td>
            <td class="px-6 py-4 text-sm text-gray-700">${exam.exam_type}</td>
            <td class="px-6 py-4 text-sm text-gray-700">${exam.subject}</td>
            <td class="px-6 py-4 text-sm text-gray-700">${exam.exam_time}</td>
            <td class="px-6 py-4">
                <span class="text-${getScoreColor(exam.my_score)} font-medium">${exam.my_score}分</span>
            </td>
            <td class="px-6 py-4 text-sm text-gray-700">${exam.class_avg_score}分</td>
            <td class="px-6 py-4 text-sm">
                <span class="px-2 py-1 bg-primary/10 text-primary text-xs rounded-full">${exam.class_rank}</span>
            </td>
            <td class="px-6 py-4 text-right">
                <button class="btn-view text-sm flex items-center justify-center" data-exam-id="${exam.id}">
                    <i class="fa fa-bar-chart mr-1"></i> 查看试卷
                </button>
            </td>
        </tr>
    `).join('');
};

// 根据分数获取颜色类
const getScoreColor = (score) => {
    if (score >= 85) return 'score-high';
    if (score >= 70) return 'score-medium';
    return 'score-low';
};

// 更新概览数据
const updateOverview = (summary) => {
    // 更新总考试次数
    const totalExamsElement = document.querySelector('.bg-white:first-child h3');
    if (totalExamsElement) {
        totalExamsElement.textContent = `${summary.total_exams || 0}次`;
    }

    // 更新平均得分
    const avgScoreElement = document.querySelector('.bg-white:nth-child(2) h3');
    if (avgScoreElement) {
        avgScoreElement.textContent = `${summary.avg_score || 0}分`;
    }

    // 更新优秀率
    const excellentRateElement = document.querySelector('.bg-white:nth-child(3) h3');
    if (excellentRateElement) {
        excellentRateElement.textContent = `${summary.excellent_rate || 0}%`;
    }
};

// 初始化筛选下拉框
const initFilterDropdowns = async () => {
    const filters = await fetchFilterOptions();

    // 更新考试类型下拉框
    const examTypeSelect = document.querySelector('select:first-of-type');
    if (examTypeSelect) {
        const currentValue = examTypeSelect.value;
        examTypeSelect.innerHTML = `
            <option>全部类型</option>
            ${filters.exam_types.map(type =>
                `<option value="${type}" ${type === currentValue ? 'selected' : ''}>${type}</option>`
            ).join('')}
        `;
    }

    // 更新学科下拉框
    const subjectSelect = document.querySelectorAll('select')[1];
    if (subjectSelect) {
        const currentValue = subjectSelect.value;
        subjectSelect.innerHTML = `
            <option>全部学科</option>
            ${filters.subjects.map(subject =>
                `<option value="${subject}" ${subject === currentValue ? 'selected' : ''}>${subject}</option>`
            ).join('')}
        `;
    }
};

// 初始化页面
const initExamRecordsPage = async () => {
    // 获取并渲染数据
    const data = await fetchExamRecords();
    renderExamTable(data.exams);
    updateOverview(data.summary);

    // 初始化筛选下拉框
    await initFilterDropdowns();

    // 设置筛选事件监听
    setupFilterListeners();

    //初始化查看试卷
    setupViewExamPaper();
    // 初始化成绩趋势图
    await initScoreTrendChart();
};

// 设置筛选监听器
const setupFilterListeners = () => {
    const filterElements = document.querySelectorAll('select, input[type="text"]');

    filterElements.forEach(element => {
        element.addEventListener('change', handleFilterChange);
        element.addEventListener('input', debounce(handleFilterChange, 300));
    });
};

// 防抖函数
const debounce = (func, wait) => {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
};

// 处理筛选变化
const handleFilterChange = async () => {
    const filters = {
        examType: document.querySelector('select:first-of-type').value,
        subject: document.querySelectorAll('select')[1].value,
        timeRange: document.querySelectorAll('select')[2].value,
        search: document.querySelector('input[type="text"]').value
    };

    const data = await fetchExamRecords(filters);
    renderExamTable(data.exams);
    updateOverview(data.summary);
};

// 查看试卷详情功能
const setupViewExamPaper = () => {
    const modal = document.getElementById('examDetailModal');
    const closeModal = document.getElementById('closeModal');
    const closeModalBtn = document.getElementById('closeModalBtn');
    const questionsContainer = document.getElementById('questionsContainer');

    // 关闭模态框
    const closeModalHandler = () => {
        modal.classList.add('hidden');
    };

    closeModal.addEventListener('click', closeModalHandler);
    closeModalBtn.addEventListener('click', closeModalHandler);

    // 点击模态框外部关闭
    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            closeModalHandler();
        }
    });

    // 为查看按钮添加事件监听（使用事件委托）
    document.addEventListener('click', async (e) => {
        if (e.target.closest('.btn-view')) {
            const button = e.target.closest('.btn-view');
            const row = button.closest('tr');
            const examId = row.querySelector('td:first-child').textContent;

            // 实际应该从数据属性获取exam_id，这里假设第一列是ID
            // 在实际应用中，您应该在渲染时设置data-exam-id属性
            await showExamDetail(parseInt(examId));
        }
    });
};

// 显示试卷详情
const showExamDetail = async (examId) => {
    try {
        const modal = document.getElementById('examDetailModal');
        const modalTitle = document.getElementById('modalExamTitle');
        const modalExamType = document.getElementById('modalExamType');
        const modalExamSubject = document.getElementById('modalExamSubject');
        const modalExamTime = document.getElementById('modalExamTime');
        const modalExamScore = document.getElementById('modalExamScore');
        const questionsContainer = document.getElementById('questionsContainer');

        // 显示加载状态
        questionsContainer.innerHTML = `
            <div class="flex justify-center items-center py-8">
                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                <span class="ml-2 text-gray-500">加载中...</span>
            </div>
        `;

        modal.classList.remove('hidden');

        // 获取考试详情
        const response = await fetch(`/api/exam_records/${examId}/detail`);
        const result = await response.json();

        if (!result.success) {
            throw new Error(result.error);
        }

        const { exam, questions } = result.data;

        // 更新模态框头部信息
        modalTitle.textContent = exam.name;
        modalExamType.textContent = exam.exam_type;
        modalExamSubject.textContent = exam.subject;
        modalExamTime.textContent = exam.exam_time;
        modalExamScore.textContent = `${exam.total_score}分 (总分: ${exam.max_total_score}分)`;

        // 渲染题目
        questionsContainer.innerHTML = questions.map((q, index) => {
            // 格式化学生答案显示
            let studentAnswerDisplay = '未作答';
            let studentAnswerClass = 'text-gray-400';

            if (q.student_answer) {
                studentAnswerDisplay = q.student_answer;
                studentAnswerClass = q.is_correct ? 'text-score-high font-medium' : 'text-score-low';
            }

            // 格式化正确答案显示
            let correctAnswerDisplay = q.correct_answer || '无';
            let correctAnswerClass = 'text-score-high font-medium';

            return `
            <div class="border border-gray-200 rounded-lg p-4 mb-4">
                <div class="flex items-start justify-between mb-3">
                    <div class="flex items-center">
                        <span class="bg-primary text-white text-sm font-medium px-2 py-1 rounded mr-2">第${index + 1}题</span>
                        <span class="text-sm text-gray-500">${q.type} · ${q.score}/${q.max_score}分</span>
                    </div>
                    <span class="px-2 py-1 text-xs rounded-full ${q.is_correct ? 'bg-score-high/20 text-score-high' : 'bg-score-low/20 text-score-low'}">
                        ${q.is_correct ? '正确' : q.student_answer ? '错误' : '未作答'}
                    </span>
                </div>

                <div class="mb-4">
                    <p class="text-gray-800 font-medium">${q.question}</p>
                </div>

                ${q.options && q.options.length > 0 ? `
                    <div class="mb-4">
                        <h4 class="text-sm font-medium text-gray-700 mb-2">选项：</h4>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-2">
                            ${q.options.map(opt => {
                                const isCorrectOption = q.correct_answer && q.correct_answer.includes(opt.label);
                                const isStudentAnswer = q.student_answer && q.student_answer.includes(opt.label);
                                let optionClass = 'flex items-center p-2 border rounded-lg';

                                if (isCorrectOption) {
                                    optionClass += ' bg-score-high/10 border-score-high';
                                } else if (isStudentAnswer && !isCorrectOption) {
                                    optionClass += ' bg-score-low/10 border-score-low';
                                }

                                return `
                                <div class="${optionClass}">
                                    <span class="font-medium mr-2">${opt.label}.</span>
                                    <span>${opt.content}</span>
                                    ${isCorrectOption ? '<span class="ml-auto text-score-high text-sm">✓</span>' : ''}
                                    ${isStudentAnswer && !isCorrectOption ? '<span class="ml-auto text-score-low text-sm">✗</span>' : ''}
                                </div>
                                `;
                            }).join('')}
                        </div>
                    </div>
                ` : ''}

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <h4 class="text-sm font-medium text-gray-700 mb-1">你的答案：</h4>
                        <div class="p-3 bg-gray-50 rounded border">
                            <span class="${studentAnswerClass}">
                                ${studentAnswerDisplay}
                            </span>
                        </div>
                    </div>
                    <div>
                        <h4 class="text-sm font-medium text-gray-700 mb-1">正确答案：</h4>
                        <div class="p-3 bg-score-high/10 border border-score-high rounded">
                            <span class="${correctAnswerClass}">${correctAnswerDisplay}</span>
                        </div>
                    </div>
                </div>

                ${q.type === '简答题' || q.type === '填空题' ? `
                    <div class="mt-3 p-3 bg-blue-50 border border-blue-200 rounded">
                        <h4 class="text-sm font-medium text-blue-700 mb-1">评分：</h4>
                        <span class="text-blue-600">${q.score} / ${q.max_score} 分</span>
                    </div>
                ` : ''}
            </div>
            `;
        }).join('');

    } catch (error) {
        console.error('加载试卷详情失败:', error);
        questionsContainer.innerHTML = `
            <div class="text-center py-8 text-gray-500">
                <i class="fa fa-exclamation-triangle text-4xl mb-2 text-yellow-500"></i>
                <p class="text-lg font-medium mb-2">加载试卷详情失败</p>
                <p class="text-sm mb-4">${error.message}</p>
                <button onclick="location.reload()" class="btn-primary mt-2">重新加载</button>
            </div>
        `;
    }
};
// 更新成绩趋势图表初始化函数
const initScoreTrendChart = async () => {
    const trendData = await fetchScoreTrend();

    const ctx = document.getElementById('scoreTrendChart').getContext('2d');
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: trendData.labels,
            datasets: [
                {
                    label: '我的得分',
                    data: trendData.student_scores,
                    borderColor: '#165DFF',
                    backgroundColor: 'rgba(22, 93, 255, 0.1)',
                    tension: 0.3,
                    fill: true,
                    pointBackgroundColor: '#165DFF',
                    pointRadius: 4,
                    pointHoverRadius: 6
                },
                {
                    label: '班级平均分',
                    data: trendData.class_avg_scores,
                    borderColor: '#94A3B8',
                    backgroundColor: 'rgba(148, 163, 184, 0.1)',
                    tension: 0.3,
                    fill: true,
                    pointBackgroundColor: '#94A3B8',
                    pointRadius: 4,
                    pointHoverRadius: 6
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                }
            },
            scales: {
                y: {
                    beginAtZero: false,
                    min: 50,
                    max: 100,
                    grid: {
                        drawBorder: false,
                    }
                },
                x: {
                    grid: {
                        display: false
                    }
                }
            }
        }
    });
};

// 在页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    setupRoleSwitch();
    setupViewExamPaper();
    initExamRecordsPage();
});


  </script>
</body>
</html>